# Title: 微信云鸽提单工具

import re
from datetime import datetime, timedelta
import python_calamine


def xlsx_to_dict(file: str, sheet_index=0) -> list[dict]:
    with open(file, 'rb') as file:
        workbook = python_calamine.CalamineWorkbook.from_filelike(file)
        _rows = iter(workbook.get_sheet_by_index(sheet_index).to_python())
        headers = list(map(str, next(_rows)))
        _values = [dict(zip(headers, row)) for row in _rows]

    return _values


def base_filter(_data, host):
    for x in _data:
        if x['管理IP'] and x['IPMIIP']:
            if x['管理IP'].strip() == host or x['IPMIIP'].strip() == host:
                return x


def server_filter(_data, host):
    for x in _data:
        if x['管理网IP'] and x['IPMI地址']:
            if x['管理网IP'].strip() == host or x['IPMI地址'].strip() == host:
                return x


def match_values(reg, content):
    values = re.findall(reg, content, re.I)
    if values:
        return list(map(lambda x: x.strip(), values))
    else:
        return []


def main():
    total_servers = xlsx_to_dict("./depository/台账/IT云贵池设备台账.xlsx", 0)
    result_template = r"""【事件登记】
资产校验：{管理IP}(管理IP)
产品名称：机架式PC服务器
事件产生时间：{事件产生时间}
资源池：贵阳资源池
问题主题：贵池-{POD}-主机-{管理IP}-{故障类型}
事件描述：贵池-{POD}服务器{管理IP}{故障类型}、业务系统：{应用系统}、设备名称：{设备名称}、IPMI：{IPMIIP}、管理IP：{管理IP}、机型：{设备型号}、SN(序列号)：{设备序列号}、资产编号:暂未转资 、机位:贵阳数据中心{机房}机房{机柜编号}机柜{U位信息}、故障描述：{故障描述}、维保状态：{品牌}
一级部门：中移信息
二级部门：基础平台部
事件一级分类：设备故障
事件二级分类：主机
事件三级分类：{故障类型}
事件问题来源：{问题来源}
影响业务系统:否
优先级：低
联系人：{_name}
联系人电话：{_phone}
联系人邮箱：{_email}
事件处理人：赵文宬
"""

    def _batch(fault_from, _name, _phone, _email, order_no, result_template, host_ip, _fault_type, fault_desc):
        if fault_from == "告警同步":
            if order_no:
                fault_type_index = result_template.find("事件三级分类：{故障类型}")
                result_template = result_template[
                                  :fault_type_index] + "事件三级分类：{故障类型}\n关联工单编号：{关联工单编号}" + result_template[
                                                                                                                fault_type_index + len(
                                                                                                                    "事件三级分类：{故障类型}"):]
            else:
                return f'问题来源是： {fault_from}, 请填写工单号'

        output = []
        match_data = base_filter(total_servers, host_ip)
        if not match_data:
            return '没有查到台账信息：' + host_ip

        match_data['事件产生时间'] = (datetime.now() + timedelta(minutes=-60)).strftime('%Y-%m-%d %H:%M:%S')
        match_data['故障类型'] = _fault_type
        match_data['故障描述'] = fault_desc
        match_data['问题来源'] = fault_from

        match_data['_name'] = _name
        match_data['_phone'] = _phone
        match_data['_email'] = _email
        if order_no:
            match_data['关联工单编号'] = order_no
        result = result_template.format(**match_data)
        output.append(result)

        return '\n'.join(output)
    output = []
    if batch:
        for i in batch.strip().split('\n'):
            num = i.split('、')[1].split()
            host_ip = num[0]
            _fault_type = num[1]
            fault_info = ' '.join(num[1:])
            # _console(_ip, fault_type, *fault_info)
            res = _batch(fault_from, _name, _phone, _email, order_no, result_template, host_ip, _fault_type, fault_info)
            output.append(res)
        return '\n'.join(output)
    else:
        return _batch(fault_from, _name, _phone, _email, order_no, result_template, _ip, fault_type, fault_desc)
